import {
  getArtistList,
  getBanners,
  getHotRecommend,
  getNewAlbum,
  getPlayListDetail
} from '@/apis/recommend'
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'

interface RecommendState {
  banners: any[]
  hotRecommend: any[]
  newAlbum: any[]
  ranking: any[]
  settleSinger: any[]
}
const initialState: RecommendState = {
  banners: [],
  hotRecommend: [],
  newAlbum: [],
  ranking: [],
  settleSinger: []
}
//获取轮播图数据
export const fetchBannerDataAction = createAsyncThunk(
  'banners',
  async (_arg, { dispatch }) => {
    const res = await getBanners()
    dispatch(changeBannersAction(res.banners))
  }
)
//获取热门推荐
export const fetchHotRecommendAction = createAsyncThunk(
  'hotRecommend',
  async (_arg, { dispatch }) => {
    const res = await getHotRecommend(8)
    dispatch(changeHotRecommendAction(res.result))
  }
)
//获取新碟上架
export const fetchNewAlbumAction = createAsyncThunk(
  'newAlbum',
  async (_arg, { dispatch }) => {
    const res = await getNewAlbum()
    dispatch(changeNewAlbumAction(res.albums))
  }
)
//获取榜单
const rankingIds = [19723756, 3779629, 2884035]
export const fetchRankingDataAction = createAsyncThunk(
  'rankingData',
  (_, { dispatch }) => {
    const promises: Promise<any>[] = []
    for (const id of rankingIds) {
      promises.push(getPlayListDetail(id))
    }

    Promise.all(promises).then((res) => {
      const playlists = res
        .filter((item) => item.playlist)
        .map((item) => item.playlist)
      dispatch(changeRankingAction(playlists))
    })
  }
)
//获取入驻歌手
export const fetchSettleSingerAction = createAsyncThunk(
  'settleSinger',
  async (_arg, { dispatch }) => {
    const res = await getArtistList()
    dispatch(changeSettleSingerAction(res.artists))
  }
)

const recommendSlice = createSlice({
  name: 'recommend',
  initialState: initialState,
  reducers: {
    changeBannersAction(state, { payload }) {
      state.banners = payload
    },
    changeHotRecommendAction(state, { payload }) {
      state.hotRecommend = payload
    },
    changeNewAlbumAction(state, { payload }) {
      state.newAlbum = payload
    },
    changeRankingAction(state, { payload }) {
      state.ranking = payload
    },
    changeSettleSingerAction(state, { payload }) {
      state.settleSinger = payload
    }
  }
})
export const {
  changeBannersAction,
  changeHotRecommendAction,
  changeNewAlbumAction,
  changeRankingAction,
  changeSettleSingerAction
} = recommendSlice.actions

export default recommendSlice.reducer
